package tn.talan.itext;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class testJfreeChart {
	/* chapter12/FoobarCharts.java */
	public static JFreeChart getBarChart() {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		dataset.setValue(57, "students", "Asia");
		dataset.setValue(36, "students", "Africa");
		dataset.setValue(29, "students", "S-America");
		dataset.setValue(17, "students", "N-America");
		dataset.setValue(12, "students", "Australia");
		return ChartFactory.createBarChart("T.U.F. Students", "continent",
				"number of students", dataset, PlotOrientation.VERTICAL, false,
				true, false);
	}

	public static JFreeChart getPieChart() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("Europe", 302);
		dataset.setValue("Asia", 57);
		dataset.setValue("Africa", 17);
		dataset.setValue("S-America", 29);
		dataset.setValue("N-America", 17);
		dataset.setValue("Australia", 12);
		return ChartFactory.createPieChart("Students per continent", dataset,true, true, false);
	}

	/* chapter12/FoobarCharts.java */
	public static void convertToPdf(JFreeChart chart, int width, int height,
			String filename) {
		Document document = new Document(new Rectangle(width, height));
		try {
			PdfWriter writer;
			writer = PdfWriter.getInstance(document, new FileOutputStream(
					filename));
			document.open();
			PdfContentByte cb = writer.getDirectContent();
			PdfTemplate tp = cb.createTemplate(width, height);
			Graphics2D g2d = tp.createGraphics(width, height,
					new DefaultFontMapper());
			Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
			chart.draw(g2d, r2d);
			g2d.dispose();
			cb.addTemplate(tp, 0, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		document.close();
	}
	public static void main(String arg[])throws Exception{
		convertToPdf(testJfreeChart.getBarChart(),300,300,"BarChart.pdf");
		convertToPdf(testJfreeChart.getPieChart(),300,300,"PieChart.pdf");
		
		
	}
}